﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Model.Announcements;
using SIG.Service;
using SIG.ViewModel.Front.Announcements;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SIG.WebMVC.Controllers
{
    public class AnnouncementController : BaseController
    {
      
        private readonly IAnnouncementService _announcementService;
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public AnnouncementController(IAnnouncementService announcementService, IPageMetaService pageMetaService, IMapper mapper)
        {
           
            _announcementService = announcementService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;

        }
        // GET: Announcement       
        [SIGActionFilter]
        public ActionResult Index(int? page,  string keyword)
        {
            var announcementListVM = new AnnouncementListVM();                   

            announcementListVM.Keyword = keyword;
            announcementListVM.PageIndex = (page ?? 1) - 1;
            announcementListVM.PageSize = 10;
            int totalCount;
            var goodslist = _announcementService.GetPagedActiveElements(announcementListVM.PageIndex, announcementListVM.PageSize, announcementListVM.Keyword, out totalCount);
            var categoryVMList = _mapper.Map<List<Announcement>, List<AnnouncementVM>>(goodslist);
            announcementListVM.TotalCount = totalCount;
            announcementListVM.Announcements = new StaticPagedList<AnnouncementVM>(categoryVMList, announcementListVM.PageIndex + 1, announcementListVM.PageSize, announcementListVM.TotalCount); ;

            return View(announcementListVM);

        }

        [HttpGet]

        public ActionResult Detail(int id)
        {
            var ann = _announcementService.GetById(id);
            ann.ViewCount++;
            _announcementService.Update(ann);
            return View(ann);
        }

        public PartialViewResult LatestAnnouncements()
        {
            var ann = _announcementService.FindBy(m => !string.IsNullOrEmpty(m.Thumbnail)).OrderByDescending(m=>m.CreatedDate).FirstOrDefault();
            var anns = _announcementService.LatesterAnnouncements(4).ToList();
            LatestAnnouncementVM vm = new LatestAnnouncementVM()
            {
                AnnouncementWithThumb = _mapper.Map<AnnouncementVM>(ann),
                Announcements = _mapper.Map<List<Announcement>, List<AnnouncementVM>>(anns)
            };
            return PartialView("_LatestAnnouncements", vm);
        }
    }
}